<?php

class Empeval_UploadController extends Zend_Controller_Action {

  const HOMEPAGE_URL = 'http://vw-group.pl/';

  private $params;

  public function init() {
    if (!$this->getRequest()->isXmlHttpRequest()) {
      $this->_helper->redirector->gotoUrlAndExit(self::HOMEPAGE_URL);
      return;
    }
    $this->jsonData();
  }

  public function jsonData() {
    $this->_helper->layout->disableLayout();
    $action = $this->getRequest()->getActionName();
    $this->_helper->viewRenderer->setNoRender(true);
    $this->_helper->contextSwitch()
            ->addActionContext($action, 'json')
            ->setAutoJsonSerialization(true)
            ->initContext('json');
    $this->getRequest()->setParam('format', 'json');
  }

  public function uploadAction() {
  	$response = new stdClass();
	  if (!empty($_FILES)) {
	  	$targetFolder = APPLICATION_PATH . Empeval_Config::getInstance()->fileUploader->uploadDir;
	  	Core_Tools::createDir($targetFolder);
			$tempFile = $_FILES['file']['tmp_name'];
			$systemFileName = md5($_FILES['file']['name'] . rand() . microtime()) . Core_Tools::getFileExtension($_FILES['file']['name']);
			$targetFile = $targetFolder . $systemFileName;

			move_uploaded_file($tempFile, $targetFile);
			$response->status = true;
			$response->fileName = $systemFileName;
			$this->view->response = $response;
			return;
		}
		$response->status = false;
		$this->view->response = $response;
  }

}